<?php

declare(strict_types=1);

namespace App\Controller\Api\v1;

use App\Controller\AbstractController;
use App\Master\Framework\Library\Easywechat\MiniApp;
use App\Master\Framework\Library\Easywechat\PayService;
use App\Request\Api\v1\WechatMiniAppCode;
use App\Utils\AppResult;

/**
 * Wechat
 * 示例
 */
class WechatController extends AbstractController
{
    // 日志模块名称
    const LOG_MODULE = 'v1/WechatController';

    /**
     * 小程序授权
     *
     * @param WechatMiniAppCode $request
     * @return string
     * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
     */
    public function miniAppCode(WechatMiniAppCode $request): string
    {
        $params = $request->validated();
        $mini = new MiniApp();
        if (!$mini->jscode2session($params['code'] ?? '')){
            return AppResult::response201($mini->getMessage(),$mini->getData());
        }
        /**
         * ==== 返回值示例 ====
         * {"session_key": "session_key-xxx","openid": "openid-xxx"}
         */
        return AppResult::response200($mini->getMessage(),$mini->getData());
    }

    /**
     * 小程序手机号授权
     *
     * @param WechatMiniAppCode $request
     * @return string
     * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
     */
    public function miniAppPhone(WechatMiniAppCode $request): string
    {
        $params = $request->validated();
        $mini = new MiniApp();
        if (!$mini->getUserPhone($params['code'] ?? '')){
            return AppResult::response201($mini->getMessage(),$mini->getData());
        }
        /**
         * ==== 返回值示例 ====
         * {
         *     "errcode": 0,
         *     "errmsg": "ok",
         *     "phone_info": {
         *         "phoneNumber": "158xxxxxxxx",
         *         "purePhoneNumber": "158xxxxxxxx",
         *         "countryCode": "86",
         *         "watermark": {
         *             "timestamp": 1709534957,
         *             "appid": "wxcced716f40d8b84b"
         *         }
         *     }
         * }
         */
        return AppResult::response200($mini->getMessage(),$mini->getData());
    }

    /**
     * 小程序支付
     *
     * @return string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
     */
    public function miniAppPay()
    {
        $openid = 'oflOP6qqIN7-mNbpgL38Pp8wXvVs';
        $order_no = time().rand(10,99);
        $pay = new PayService();
        if (!$pay->jsapi($openid,$order_no,1,'测试','http://hyperf.yangertao.com')){
            return AppResult::response201($pay->getMessage(),$pay->getData());
        }
        return AppResult::response200($pay->getMessage(),$pay->getData());
    }
}